<?php

namespace app\admin\controller;

use app\admin\model\AdminCate;
use app\admin\model\AdminCateRelation;
use app\admin\model\Dictionary;
use app\admin\model\Project as projectModel;
use think\Session;

class Working extends Permissions
{
    /**
     * 人员看板
     * @return mixed|void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function index()
    {
        $post = $this->request->param();
        //dump($post);

        $person_ids = '';
        if (isset($post['person_ids']) && !empty($post['person_ids'])) {
            $person_ids = $post['person_ids'];
        }
        //开始时间与结束时间都没
        if (empty($post['begin_time']) && empty($post['end_time'])) {
            $post['begin_time'] = date("Y-m-d");
            $post['end_time'] = date('Y-m-d', strtotime(" +1 month") - 1);
        }

        if ((isset($post['begin_time']) && !empty($post['begin_time'])) && (!isset($post['end_time']) || empty($post['end_time']))) {//开始时间设置了，结束时间没设置
            $post['end_time'] = date('Y-m-d', strtotime($post['begin_time'] . ' +1 month')-1);
        }
        if ((!isset($post['begin_time']) || empty($post['begin_time'])) && (isset($post['end_time']) && !empty($post['end_time']))) {//开始时间没设置，结束时间设置
            $post['begin_time'] = date('Y-m-d', strtotime($post['end_time'] . ' -1 month'));
        }

        $days = (strtotime($post['end_time']) - strtotime($post['begin_time'])) / 24 / 60 / 60;
        if ($days > 61) {
            return $this->error('最多查询二个月时间');
        }
        //获取每一天
        $date = $this->getDateFromRange($post['begin_time'], $post['end_time']);

        //var_dump($date);die;
        $search_type = !empty($post['search_type']) ? $post['search_type'] :0;
        $where = [];
        $role_id = 0;
        if (isset($post['role_id']) && !empty($post['role_id']) && $search_type == 1) {
            $where["r.cate_id"] = $post['role_id'];
            $role_id = $post['role_id'];
        }elseif ($search_type == 3){
            $where['p.id'] = ['in', explode(',',$person_ids)];
        }

//        var_dump($where);

        //获取角色列表
        $roleModel = new AdminCate();
        $roleList = $roleModel->field("id as role_id , name as role_name")->where(['is_prd' => 0])->select();

        //查询人员
        $adminModel = new \app\admin\model\Admin();
        $personList = [];
//        $post['search_type'] == 2 查全部
        if ($where || $search_type == 2) {
            $where['p.is_prd'] = 0;
            $personList = $adminModel->alias("p")
                ->field("p.id as person_id, p.nickname as person_name")
                ->join("tplay_admin_cate_relation r", "r.admin_id = p.id", 'right')
                ->where($where)
                ->group("p.id")
                ->order(['p.name' => 'asc'])
                ->select();
        }

        $personIds = [];
        $perList = [];
        foreach ($personList as $val) {
            $personIds[] = $val['person_id'];
            $perList[$val['person_id']]['person_id'] = $val['person_id'];
            $perList[$val['person_id']]['person_name'] = $val['person_name'];
            $perList[$val['person_id']]['task_list'] = [];
        }//dump($post);dump($perList);die;


        //查询任务
        $taskModel = new \app\admin\model\Task();
        $b_time = strtotime($post['begin_time'] . ' 00:00:00');
        $e_time = strtotime($post['end_time'] . ' 23:59:59');
        $where_task['t.begin_time'] = ["elt", $e_time];
        $where_task['t.end_time'] = ["egt", $b_time];
        $where_task["tr.person_id"] = ["in", $personIds];
        $where_task['t.is_del'] = 0;
        $taskList = $taskModel->alias("t")
            ->field("t.begin_time, t.end_time, t.task_id, tr.person_id, tr.person_name,t.task_name,t.project_id, t.task_status, p.project_name")
            ->join("tplay_task_person_relation tr", "tr.task_id = t.task_id and tr.relation_status = 10", "right")
            ->join('tplay_project p','t.project_id = p.project_id','left')
            ->where($where_task)->select();

        //dump($taskList);
        foreach ($taskList as $task) {
            $t_list = [];
            $t_list['task_id'] = $task['task_id'];
            $t_list['begin_time'] = $task['begin_time'];
            $t_list['end_time'] = $task['end_time'];
            $t_list['task_name'] = $task['task_name'];
            $t_list['project_id'] = $task['project_id'];
            $t_list['project_name'] = $task['project_name'];
            $t_list['task_status'] = $task['task_status'];
            $perList[$task['person_id']]["task_list"][] = $t_list;

        }
        foreach ($perList as &$pe) {
            $days_time = [];
            foreach ($date as $da) {
                $one_time = [];
                $one_time['type'] = 2;//1在，2不在
                $one_time['date'] = $da['day'];
                $one_time['years'] = date("Y", $da['time']);
                $one_time['months'] = date("m", $da['time']);
                $one_time['week'] = $da['week'];
                $one_time['task_content'] = "";
                $task_content = [];
                $task_downLoad_content = [];
                foreach ($pe['task_list'] as $ta) {
                    $da_time = $da['time'];
                    if ($da_time >= $ta["begin_time"] && $da_time <= $ta['end_time']) {
                        $one_time['type'] = 1;
                        $task_content[] = $ta['project_id'] . '.' . $ta['project_name'] . ' - ' . $ta['task_name'];
                        $task_downLoad_content[] = $ta['project_id'] . '.' . $ta['project_name'] . ' - ' . $ta['task_name'];
                    }
                }
                if (empty($task_content)) {
                    $task_content[] = '回血中...';
                    //$task_downLoad_content[] = '';
                }
                $one_time['task_content'] = implode('<br/>', $task_content);
                $one_time['task_downLoad_content'] = implode("  ", $task_downLoad_content);
                $days_time[] = $one_time;
            }
            $pe["date_list"] = $days_time;
        }
//        dump($perList);
//        $adminCateMode = new AdminCate();
//        $adminCateRelationModel = new AdminCateRelation();
//        //获取角色列表
//        $personRoleList = $adminCateMode->select();
//        foreach ($personRoleList as &$ro) {
//            $relationList = $adminCateRelationModel->where(['admin_id' => $ro['id'], "cate_status" => 1])->select();
//            $ro['person_list'] = $relationList;
//        }

        //生成表格
        if ($this->request->isAjax()) {
            if (empty($perList)) {
                $this->error("没有数据,请重新选择...");
            }
            $file_dir = '/tmp/excel_' . session_id() . '_jian.xls';
            $str = '';
            $str .= '<html xmlns="http://www.w3.org/1999/xhtml">';
            $str .= '<head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> </head>';
            $str .= '<body><table border=1>';
            $str .= "<thead><tr><th align='center'>人员日期</th>";
            foreach ($date as $day) {
                $str .= "<th align='center'>{$day['day']}</th>";
            }
            $str .= "</tr></thead>";
            $str .= "<tbody>";
            foreach ($perList as $info) {
                $str .= "<tr><td height='40' nowrap='nowrap' align='center'>{$info['person_name']}</td>";

                foreach ($info['date_list'] as $date_list) {
                    $str .= "<td nowrap='nowrap'>{$date_list['task_downLoad_content']}</td>";
                }

                $str .= '</tr>';

            }
            $str .= '</tbody> </table>';
            //echo $str;
            file_put_contents($file_dir, $str);
            return $this->success('导出成功', "admin/working/download", null, 3);
        }


        $this->assign("info", $perList);
        $this->assign("days", $date);
        $this->assign("role", $roleList);
        $this->assign("role_id", $role_id);
        $this->assign("personList", $personList);
        $this->assign("person_ids", $person_ids);
        //$this->assign("personRoleList", $personRoleList);
        $this->assign("begin_time", $post['begin_time']);
        $this->assign("end_time", $post['end_time']);
        $this->assign("search_type", $search_type);
        return $this->fetch();
    }

    public function getDateFromRange($startdate, $enddate)
    {

        $stimestamp = strtotime($startdate . ' 00:00:00');
        $etimestamp = strtotime($enddate . ' 23:59:59');

        // 计算日期段内有多少天
        $days = ($etimestamp - $stimestamp) / 86400;

        // 保存每天日期
        $date = [];

        for ($i = 0; $i < $days; $i++) {
            $tmp['time'] = $stimestamp + (86400 * $i);
            $tmp['day'] = date('m-d', $stimestamp + (86400 * $i));
            $tmp['week'] = date('w',$tmp['time']);
            $date[] = $tmp;
            unset($tmp);
        }

        return $date;
    }

    /**
     * 工作日历
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function detail()
    {
        $post = $this->request->param();
        $where = [];
//        if (empty($post['person_id'])){
//            $post['person_id'] = Session::get('admin');
//        }

        if (empty($post['date'])) {
            $begin = date("Y-m-01");
            $end = date('Y-m-d', strtotime(date('Y-m') . "-01 +1 month") - 1);
        } else {
            $begin = date("Y-m-01", strtotime($post['date']));
            $end = date('Y-m-d', strtotime($post['date'] . "-01 +1 month") - 1);
        }

        if (!isset($post["person_id"]) || empty($post["person_id"]) && (!isset($post['person_name']) || empty($post['person_name']))) {
            //获取人员列表
            $adminModel = new \app\admin\model\Admin();
            $personList = $adminModel->field("id as person_id, nickname as person_name")->where(['is_prd' => 0])->order(['name' => 'acs'])->select();
            $this->assign("info", []);
            $this->assign("personInfo", []);
            $this->assign("person_id", []);
            $this->assign("years", "");
            $this->assign("months", "");
            $this->assign("person_id", 0);
            $this->assign("personList", $personList);
            $this->assign("date", date("Y-m", strtotime($begin)));
            $this->assign('taskStatusColorMap', Dictionary::taskStatusColorMap());

            return $this->fetch();
        }


        $where["t.begin_time"] = ["elt", strtotime($end)];
        $where["t.end_time"] = ["egt", strtotime($begin)];
        //if (isset($post["person_status"]) && !empty($post["person_status"])) $where['person_status'] = $post["person_status"];
        $person_id = 0;
        if (isset($post["person_name"]) && !empty($post["person_name"])) {
            $where['pr.person_name'] = ['like', $post["person_name"]];
            $where_p['r.admin_name'] = ['like', $post["person_name"]];
        } else {
            $where['pr.person_id'] = (int)$post["person_id"];
            $where_p['r.admin_id'] = (int)$post["person_id"];
            $person_id = (int)$post["person_id"];
        }
        $where['relation_status'] = 10;
        //查询人员
        $adminCateModel = new \app\admin\model\AdminCate();
        $personList = $adminCateModel->alias("p")
            ->field("r.admin_id as person_id, r.admin_name as person_name, p.name as role_name")
            ->join("tplay_admin_cate_relation r", "r.cate_id = p.id", 'right')
            ->where($where_p)
            ->select();
        $personInfo = [];
        $roles = [];
        foreach ($personList as $person) {
            $person_id = $person['person_id'];
            $personInfo['person_id'] = $person['person_id'];
            $personInfo['person_name'] = $person['person_name'];
            $roles[] = $person['role_name'];
        }
        $personInfo['roles'] = implode(",", $roles);
//        dump($personInfo);die;
        $taskModel = new \app\admin\model\Task();
        $where['t.is_del'] = 0;
        $personList = $taskModel->alias("t")
            ->field("pr.person_id,t.task_id,t.task_name,t.task_status, t.project_id,t.begin_time,t.end_time,t.task_type")
            ->join("tplay_task_person_relation pr", "pr.task_id = t.task_id and pr.relation_status = 10", "right")
            ->where($where)
            ->select();
        //dump($personList);echo $taskModel->getLastSql();
        //获取每一天
        $data = $this->getDateFromRange($begin, $end);//dump($data);

        $days_time = [];
        foreach ($data as $dnum => $da) {
            $one_time = [];
            $one_time['num'] = $dnum + 1;
            $one_time['type'] = 2;//1在，2不在
            $one_time['date'] = date('Y-m-d', $da['time']);
            $one_time['week'] = date("w", $da['time']);

            $one_time['task_list'] = [];
            foreach ($personList as $ta) {
                $taskList = [];
                $da_time = $da['time'];
                if ($da_time >= $ta["begin_time"] && $da_time <= $ta['end_time']) {
                    $one_time['type'] = 1;
                    $taskList['task_id'] = $ta['task_id'];
                    $taskList['task_name'] = $ta['task_name'];
                    $taskList['task_status'] = $ta['task_status'];
                    $taskList['task_type'] = $ta['task_type'];
                    $taskList['project_id'] = $ta['project_id'];
                    $one_time['task_list'][] = $taskList;
                }
            }
            $days_time[] = $one_time;
        }
        //$one_day = $days_time[0];
        $begin_week = date("w", strtotime($begin));
        //echo $begin_week;
        if ($begin_week > 0) {
            for ($i = 0; $i < $begin_week; $i++) {
                $e_data = [];
                $e_data['num'] = 0;
                $e_data['type'] = 2;
                $e_data['date'] = date("Y-m-d", strtotime("-" . ($i + 1) . " days", strtotime($begin)));
                $e_data['week'] = date("w", strtotime($e_data['date']));
                $e_data['task_list'] = [];
                array_unshift($days_time, $e_data);
            }
        }
        $end_week = date("w", strtotime($end));
        if ($end_week < 6) {
            for ($ii = 0; $ii < (6 - $end_week); $ii++) {
                $eb_data = [];
                $eb_data['type'] = 2;
                $eb_data['num'] = 0;
                $eb_data['date'] = date("Y-m-d", strtotime(($ii + 1) . " days", strtotime($end)));
                $eb_data['week'] = date("w", strtotime($eb_data['date']));
                $eb_data['task_list'] = [];
                array_push($days_time, $eb_data);
            }
        }

        $list = [];
        foreach ($days_time as $k => $v) {
            $key = ceil(($k + 1) / 7);
            $list[$key - 1][] = $v;
        }
        //dump($list);
        //获取人员列表
        $adminModel = new \app\admin\model\Admin();
        $personList = $adminModel->field("id as person_id, nickname as person_name")->where(['is_prd' => 0])->order(['name' => 'acs'])->select();
        $this->assign("info", $list);
        $this->assign("personInfo", $personInfo);
        $this->assign("person_id", $person_id);
        $this->assign("personList", $personList);
        $this->assign("years", date("Y", strtotime($begin)));
        $this->assign("months", date("m", strtotime($begin)));
        $this->assign("date", date("Y-m", strtotime($begin)));
        $this->assign("person_id", $post["person_id"]);
        $this->assign("dates", date("Y", strtotime($begin)) . "年" . date("m", strtotime($begin)) . "月");
        $this->assign('taskStatusColorMap', Dictionary::taskStatusColorMap());
        return $this->fetch();
    }

    /**
     * 项目看板
     * @return mixed|void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function projectIndex()
    {
        $post = $this->request->param();

        //开始时间与结束时间都没
        if (empty($post['begin_time']) && empty($post['estimate_time'])) {
            $post['begin_time'] = date("Y-m-d");
            $post['estimate_time'] = date('Y-m-d', strtotime(" +2 month") - 1);
        }

        if ((isset($post['begin_time']) && !empty($post['begin_time'])) && (!isset($post['estimate_time']) || empty($post['estimate_time']))) {//开始时间设置了，结束时间没设置

            //dump($post['begin_time']);
            $post['estimate_time'] = date('Y-m-d', strtotime($post['begin_time'] . ' +2 month')-1);
        }
        if ((!isset($post['begin_time']) || empty($post['begin_time'])) && (isset($post['estimate_time']) && !empty($post['estimate_time']))) {//开始时间没设置，结束时间设置

            $post['begin_time'] = date('Y-m-d', strtotime($post['estimate_time'] . ' -2 month'));
        }//dump($post);die;

        $days = (strtotime($post['estimate_time']) - strtotime($post['begin_time'])) / 24 / 60 / 60;
        if ($days > 92) {
            return $this->error('最多查询三个月时间');
        }
        //获取每一天
        $date = $this->getDateFromRange($post['begin_time'], $post['estimate_time']);
        $where = [];
        $where['is_del'] = 0;
        $project_type = 0;
        if (isset($post['project_type']) && !empty($post['project_type'])) {
            $where['project_type'] = $post['project_type'];
            $project_type = $post['project_type'];
        }
        $project_status = 0;
        if (isset($post['project_status']) && !empty($post['project_status'])) {
            $where['project_status'] = $post['project_status'];
            $project_status = $post['project_status'];
        }

        $where['begin_time'] = ["elt", strtotime($post['estimate_time'] . ' 23:59:59')];
        $where['estimate_time'] = ["egt", strtotime($post['begin_time'] . ' 00:00:00')];
        $projectModel = new \app\admin\model\Project();
        $project = $projectModel->where($where)->select();
        //echo $projectModel->getLastSql();
        $projectList = [];

        $taskModel = new \app\admin\model\Task();
        foreach ($project as &$pr) {
            $one_day = [];
            $pr['project_text'] = "";
            $taskList = $taskModel->where(['is_del'=>0, "project_id"=>$pr['project_id']])->select();
            foreach ($date as $data) {
                $type = 2;// 1有 2否
                if ($data['time'] >= $pr['begin_time'] && $data['time'] <= $pr['estimate_time']) {
                    $type = 1;
                }
                $t_type = 4;//1浅蓝开发任务 2黄测试任务 3红其他(都有), 4蓝当天没有任务

                if ($type == 1){
                    $arr = [];
                    foreach ($taskList as $ta){
                        if (in_array($ta['task_type'], Dictionary::taskTypeClass("dev")) && $data['time']>= $ta['begin_time'] && $data['time'] <=$ta['end_time']){
                            array_push($arr, 1);
                        }
                        if (in_array($ta['task_type'],Dictionary::taskTypeClass("test")) && $data['time']>= $ta['begin_time'] && $data['time'] <=$ta['end_time']){
                            array_push($arr, 2);
                        }
                    }
                    if (in_array(1,$arr) && in_array(2, $arr)){
                        $t_type = 3;
                    }elseif (in_array(1,$arr) && !in_array(2, $arr)){
                        $t_type = 1;
                    }elseif (!in_array(1,$arr) && in_array(2, $arr)){
                        $t_type = 2;
                    }
                }
                $one_time['type'] = $type;
                $one_time['t_type'] = $t_type;
                $one_day[] = $one_time;
            }
            $pr["date_list"] = $one_day;
            $pr['project_text'] = $pr['project_id'] . "." . $pr['project_name'];
        }//dump($project);die;
        $this->assign("info", $project);
        $this->assign("days", $date);
        $this->assign("project_status", $project_status);
        $this->assign("project_type", $project_type);
        $this->assign("begin_time", $post['begin_time']);
        $this->assign("estimate_time", $post['estimate_time']);
        $this->assign("projetcTypeName", Dictionary::projetcTypeName());
        $this->assign("projectStatusName", Dictionary::projectStatusName());
        return $this->fetch();
    }

    //导出表格
    public function download()
    {
        //echo 'download';die;
        $file_dir = '/tmp/excel_' . session_id() . '_jian.xls';
        header("Content-type:application/vnd.ms-excel");
        header('Content-Disposition: attachment;filename="人员看板.xls"');
        header('Cache-Control: max-age=0');
        echo file_get_contents($file_dir);
        unlink($file_dir);
    }

    /**
     * 人员弹窗
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function userIframe(){
        $adminCateMode = new AdminCate();
        $adminCateRelationModel = new AdminCateRelation();
        //获取角色列表
        $roleList = $adminCateMode->where(['is_prd'=>0])->select();
        foreach ($roleList as &$ro) {
            $relationList = $adminCateRelationModel->where(['cate_id' => $ro['id'], "cate_status" => 1])->order('admin_name asc')->select();
            $ro['person_list'] = $relationList;
        }
        $personId = [];
        $this->assign('presonRoleList', $roleList);
        $this->assign('personIds', $personId);
        return $this->fetch();
        //return $roleList;
    }
}